package train;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @description:图片的加密
 * @author:Mr.Cat
 * @create:2021-11-09 16:43
 **/
public class PicTest {
    @Test
    public void test1() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("MM.png");
            fos = new FileOutputStream("mm1secret.png");

            byte [] buffer = new byte[20];
            int len;
            while((len=fis.read(buffer))!=-1){
                //字节数组进行修改
                //错误方法：
    //            for(byte b:buffer){
    //                b=(byte)(b^5);
    //            }
                //正确方法：
                for(int i=0;i<len;i++){
                    buffer[i]= (byte) (buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (fos!=null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    //图片的解密
    @Test
    public void test2() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("mm1secret.png");
            fos = new FileOutputStream("mm2secret.png");

            byte [] buffer = new byte[20];
            int len;
            while((len=fis.read(buffer))!=-1){
                //字节数组进行修改
                //错误方法：
                //            for(byte b:buffer){
                //                b=(byte)(b^5);
                //            }
                //正确方法：
                for(int i=0;i<len;i++){
                    buffer[i]= (byte) (buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (fos!=null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

